package org.or5e.oss.ws;

import java.util.HashMap;
import java.util.Map;

import org.or5e.oss.core.BaseObject;
import org.or5e.oss.ws.datatypes.Warning;
import org.or5e.oss.ws.datatypes.Warning.WarningType;
import org.or5e.oss.ws.datatypes.signin.SignInRequest;
import org.or5e.oss.ws.datatypes.signin.SignInResponse;
import org.or5e.oss.ws.helper.SignInServiceHelper;

/**
 * Core service use to validate the Sign In process. This will hold the small local cache to have the user login information. This will be the sub request processor for the signing in transaction.
 * @author Ponraj Suthanthiramani
 */
public class SignInService extends BaseObject implements Service {
	private Map<String, UserInfo> localCache = new HashMap<String, UserInfo>();

	/**
	 * Process method, which will get the request from the main processing API, so that it acts as the sub processing system.
	 * {@link Service}
	 */
	public Object processMessage(Object _request) {
		SignInRequest _signInReq = (SignInRequest) _request;
		SignInResponse _signInRes = new SignInResponse();
		
		String userKey = _signInReq.getUserKey();
		String userPass = _signInReq.getUserPass();
		info("User is trying to login :"+userKey);
		
		UserInfo userInfo = localCache.get(userKey+"$"+userPass);

		if(userInfo == null) {
			userInfo = SignInServiceHelper.getUserAuthentication(_signInReq.getUserKey(), _signInReq.getUserPass());
		}

		if(userInfo != null) {
			_signInRes.setUserID(userInfo.getUserID());
			_signInRes.setUserKey(_signInReq.getUserKey());
			_signInRes.setUserName(userInfo.getUserName());
			_signInRes.setUserSecurityToken(userInfo.getSecurityToken());
			_signInRes.setUserStatus(userInfo.getUserStatus());
			_signInRes.setWarning(new Warning());
			localCache.put(_signInReq.getUserKey()+"#"+_signInReq.getUserPass(), userInfo);
		}
		else {
			_signInRes.setUserID(null);
			_signInRes.setUserKey(_signInReq.getUserKey());
			_signInRes.setUserName(null);
			_signInRes.setUserSecurityToken(null);
			_signInRes.setUserStatus(null);
			Warning warn = new Warning();
			warn.set_warningLevel(new Integer(3));
			warn.set_warningMessage(WarningMessage.USERAUTHFAILED);
			warn.set_warningType(WarningType.ERROR);
			_signInRes.setWarning(warn);
		}
		return _signInRes;
	}
	@Override
	public String getName() {
		return "SignInService";
	}
}